<?php

namespace App\Http\Controllers;

use App\Http\Requests\ClassMemberCreate;
use App\Models\ClassMember;
use App\Services\ClassService;
use Illuminate\Http\Request;

class ClassMemberController extends Controller
{

    public function list(Request $request)
    {
        $limit = $request->limit ?? 10;
        $status = $request->status;
        $where = [
            'class_member.school_id' => $request->school_id,
            'class_member.campus_id' => $request->campus_id,
            'class_id' => $request->class_id,
        ];

        if($status){
            $where['class_member.status'] = $status;
        }

        $res = ClassMember::where($where)
        ->with('student:id,student_name')
        ->paginate($limit);
        foreach ($res as $item) {
            $item->append('student_name');
            $item->makeHidden('student');
        }
        return resSucc(formatPage($res), "班级学员列表");
    }

    public function create(ClassMemberCreate $request)
    {

        $classMember = $request->validated();
        $classMember['school_id'] = $request->school_id;
        $classMember['campus_id'] = $request->campus_id;
        $classMember['status'] = $classMember['status'] ?? 1;

        $cMember = ClassService::IsExistClassMember($classMember['class_id'], $classMember['student_id']);

        if($cMember && $cMember->status == 1){
            return resFail(null, "学员已存在该班级");
        };

        try{
            if($cMember){
                ClassMember::where('id', $cMember->id)->update(['status'=>1]);
            }else {
                ClassMember::create($classMember);
            }
            return resSucc(null, "进班成功");
        } catch (\Exception $e) {
            return resFail($e, "进班失败");
        } catch (\Throwable $e) {
            return resFail($e, "进班失败");
        }
    }

    public function leave(Request $request){

        $class_id = $request->class_id;
        $student_id = $request->student_id;

        $classMember = ClassService::IsExistClassMember($class_id, $student_id);

        if(!$classMember){
            return resFail(null, "学员不存在");
        }

        ClassMember::where('id', $classMember->id)->update(['status' => 2]);

        return resSucc(null, "更新成功");
    }
}
